import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../common/entity/user.dart';
import '../common/services/user_service.dart';

/// 用户状态类
class UserState {
  final UserEntity? currentUser;
  final bool isLoading;
  final String? error;
  final bool isLoggedIn;

  const UserState({
    this.currentUser,
    this.isLoading = false,
    this.error,
    this.isLoggedIn = false,
  });

  UserState copyWith({
    UserEntity? currentUser,
    bool? isLoading,
    String? error,
    bool? isLoggedIn,
  }) {
    return UserState(
      currentUser: currentUser ?? this.currentUser,
      isLoading: isLoading ?? this.isLoading,
      error: error,
      isLoggedIn: isLoggedIn ?? this.isLoggedIn,
    );
  }
}

/// 用户状态管理器
class UserNotifier extends StateNotifier<UserState> {
  UserNotifier() : super(const UserState()) {
    _loadCurrentUser();
  }

  /// 加载当前用户
  void _loadCurrentUser() {
    final user = UserService.getCurrentUser();
    if (user != null) {
      state = state.copyWith(currentUser: user, isLoggedIn: true);
    }
  }

  /// 用户登录
  Future<bool> login(String username, String password) async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final user = await UserService.login(username, password);

      if (user != null) {
        state = state.copyWith(
          currentUser: user,
          isLoading: false,
          isLoggedIn: true,
        );
        return true;
      } else {
        state = state.copyWith(
          isLoading: false,
          error: 'The username or password is incorrect.',
        );
        return false;
      }
    } catch (e) {
      state = state.copyWith(isLoading: false, error: 'Login failed: $e');
      return false;
    }
  }

  /// 苹果登录
  Future<bool> signInWithApple() async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final user = await UserService.signInWithApple();

      if (user != null) {
        state = state.copyWith(
          currentUser: user,
          isLoading: false,
          isLoggedIn: true,
        );
        return true;
      } else {
        state = state.copyWith(isLoading: false, error: 'Apple Sign In failed');
        return false;
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: 'Apple Sign In failed: $e',
      );
      return false;
    }
  }

  /// 用户注册
  Future<bool> register({
    required String username,
    required String password,
    String? avatar,
  }) async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final success = await UserService.register(
        username: username,
        password: password,
        avatar: avatar,
      );

      if (success) {
        state = state.copyWith(isLoading: false);
        return true;
      } else {
        state = state.copyWith(
          isLoading: false,
          error: 'Username already exists',
        );
        return false;
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: 'Registration failed: $e',
      );
      return false;
    }
  }

  /// 用户登出
  Future<void> logout() async {
    state = state.copyWith(isLoading: true);

    try {
      await UserService.logout();
      state = const UserState();
    } catch (e) {
      state = state.copyWith(isLoading: false, error: 'Logout failed: $e');
    }
  }

  /// 更新用户信息
  Future<bool> updateUser(UserEntity user) async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final success = await UserService.updateUser(user);

      if (success) {
        state = state.copyWith(currentUser: user, isLoading: false);
        return true;
      } else {
        state = state.copyWith(
          isLoading: false,
          error: 'Update user information failed',
        );
        return false;
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: 'Update user information failed: $e',
      );
      return false;
    }
  }

  /// 添加分享记录
  Future<bool> updateShare(String shareId) async {
    try {
      final success = await UserService.addShare(shareId);
      if (success) {
        final updatedUser = UserService.getCurrentUser();
        if (updatedUser != null) {
          state = state.copyWith(currentUser: updatedUser);
        }
      }
      return success;
    } catch (e) {
      state = state.copyWith(error: 'Add share record failed: $e');
      return false;
    }
  }

  /// 修改会员
  Future<bool> updateVip() async {
    try {
      final success = await UserService.updateVip();
      if (success) {
        final updatedUser = UserService.getCurrentUser();
        if (updatedUser != null) {
          state = state.copyWith(currentUser: updatedUser);
        }
      }
      return success;
    } catch (e) {
      state = state.copyWith(error: 'Update membership failed: $e');
      return false;
    }
  }

  /// 重新加载当前用户状态
  void reloadCurrentUser() {
    final updatedUser = UserService.getCurrentUser();
    if (updatedUser != null) {
      state = state.copyWith(currentUser: updatedUser);
    }
  }

  /// 强制刷新用户状态（用于购买完成后的状态同步）
  void forceRefreshUserState() {
    // 先重新加载当前用户
    reloadCurrentUser();

    // 通过改变状态来触发所有依赖的Provider重新计算
    final currentState = state;
    state = currentState.copyWith(
      currentUser: currentState.currentUser,
      // 通过改变时间戳来强制刷新
      isLoggedIn: currentState.isLoggedIn,
    );
  }

  /// 检查用户今天是否已经发布过分享
  Future<bool> hasSharedToday() async {
    try {
      return await UserService.hasSharedToday();
    } catch (e) {
      state = state.copyWith(error: 'Check share status failed: $e');
      return false;
    }
  }

  /// 删除用户账号
  Future<bool> deleteAccount() async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final currentUser = state.currentUser;
      if (currentUser == null) {
        state = state.copyWith(
          isLoading: false,
          error: 'No current user found',
        );
        return false;
      }

      final success = await UserService.deleteAccount(currentUser.id);

      if (success) {
        // 清除状态，用户已被删除
        state = const UserState();
        return true;
      } else {
        state = state.copyWith(
          isLoading: false,
          error: 'Failed to delete account',
        );
        return false;
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: 'Delete account failed: $e',
      );
      return false;
    }
  }

  /// 清除错误信息
  void clearError() {
    state = state.copyWith(error: null);
  }
}

/// 用户状态 Provider
final userProvider = StateNotifierProvider<UserNotifier, UserState>(
  (ref) => UserNotifier(),
);

/// 当前用户 Provider（便于访问）
final currentUserProvider = Provider<UserEntity?>((ref) {
  return ref.watch(userProvider).currentUser;
});

/// 登录状态 Provider
final isLoggedInProvider = Provider<bool>((ref) {
  return ref.watch(userProvider).isLoggedIn;
});
